const WebSocket = require('ws');
const http = require('http');

// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
    // 添加基本的HTTP响应，用于测试服务器是否运行
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('WebSocket Chat Server is running!\n');
});

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ server });

// 存储连接的客户端
const clients = new Map();

console.log('WebSocket 服务器启动中...');

wss.on('connection', (ws, req) => {
    console.log('新的客户端连接');
    console.log('连接来源:', req.socket.remoteAddress);
    
    let currentUserId = null;

    ws.on('message', (message) => {
        try {
            const data = JSON.parse(message);
            console.log('收到消息:', data);

            switch (data.type) {
                case 'auth':
                    // 处理身份验证
                    currentUserId = data.userId;
                    clients.set(currentUserId, ws);
                    
                    console.log(`用户 ${currentUserId} 已连接`);
                    console.log('当前在线用户数:', clients.size);
                    
                    // 发送确认消息
                    ws.send(JSON.stringify({
                        type: 'auth',
                        status: 'success',
                        message: '身份验证成功'
                    }));
                    break;

                case 'message':
                    // 处理聊天消息
                    const { senderId, receiverId, message: msgText, timestamp } = data;
                    
                    // 检查接收者是否在线
                    const receiverWs = clients.get(receiverId);
                    
                    if (receiverWs && receiverWs.readyState === WebSocket.OPEN) {
                        // 转发消息给接收者
                        receiverWs.send(JSON.stringify({
                            type: 'message',
                            message: msgText,
                            senderId: senderId,
                            timestamp: timestamp
                        }));
                        
                        console.log(`消息已转发: ${senderId} -> ${receiverId}`);
                    } else {
                        // 接收者不在线，发送错误消息
                        ws.send(JSON.stringify({
                            type: 'system',
                            message: `用户 ${receiverId} 不在线，消息发送失败`
                        }));
                        
                        console.log(`用户 ${receiverId} 不在线`);
                    }
                    break;

                case 'voice':
                    // 处理语音消息
                    const { senderId: vSenderId, receiverId: vReceiverId, duration, audioBase64, msgId, timestamp: vTimestamp } = data;
                    const vReceiverWs = clients.get(vReceiverId);
                    if (vReceiverWs && vReceiverWs.readyState === WebSocket.OPEN) {
                        vReceiverWs.send(JSON.stringify({
                            type: 'voice',
                            duration,
                            senderId: vSenderId,
                            audioBase64,
                            msgId,
                            timestamp: vTimestamp
                        }));
                        console.log(`语音消息已转发: ${vSenderId} -> ${vReceiverId}`);
                    } else {
                        ws.send(JSON.stringify({
                            type: 'system',
                            message: `用户 ${vReceiverId} 不在线，语音消息发送失败`
                        }));
                        console.log(`用户 ${vReceiverId} 不在线`);
                    }
                    break;

                case 'image':
                    // 处理图片消息
                    const { senderId: iSenderId, receiverId: iReceiverId, fileUrl, timestamp: iTimestamp } = data;
                    const iReceiverWs = clients.get(iReceiverId);
                    if (iReceiverWs && iReceiverWs.readyState === WebSocket.OPEN) {
                        iReceiverWs.send(JSON.stringify({
                            type: 'image',
                            fileUrl,
                            senderId: iSenderId,
                            timestamp: iTimestamp
                        }));
                        console.log(`图片消息已转发: ${iSenderId} -> ${iReceiverId}`);
                    } else {
                        ws.send(JSON.stringify({
                            type: 'system',
                            message: `用户 ${iReceiverId} 不在线，图片消息发送失败`
                        }));
                        console.log(`用户 ${iReceiverId} 不在线`);
                    }
                    break;

                default:
                    console.log('未知消息类型:', data.type);
            }
        } catch (error) {
            console.error('解析消息失败:', error);
            ws.send(JSON.stringify({
                type: 'system',
                message: '消息格式错误'
            }));
        }
    });

    ws.on('close', () => {
        if (currentUserId) {
            clients.delete(currentUserId);
            console.log(`用户 ${currentUserId} 已断开连接`);
            console.log('当前在线用户数:', clients.size);
        }
    });

    ws.on('error', (error) => {
        console.error('WebSocket 错误:', error);
        if (currentUserId) {
            clients.delete(currentUserId);
        }
    });
});

// 启动服务器
const PORT = process.env.PORT || 8080;
server.listen(PORT, '0.0.0.0', () => {
    console.log('='.repeat(50));
    console.log(`WebSocket 服务器启动成功！`);
    console.log(`HTTP 服务器: http://localhost:${PORT}`);
    console.log(`WebSocket URL: ws://localhost:${PORT}`);
    console.log('='.repeat(50));
    console.log('等待客户端连接...');
});

// 错误处理
server.on('error', (error) => {
    if (error.code === 'EADDRINUSE') {
        console.error(`错误: 端口 ${PORT} 已被占用`);
        console.error('请尝试以下解决方案:');
        console.error(`1. 停止占用端口 ${PORT} 的其他程序`);
        console.error(`2. 使用不同的端口: PORT=8081 node websocket-server.js`);
        console.error(`3. 在Windows上查看端口占用: netstat -ano | findstr :${PORT}`);
        console.error(`4. 在Linux/Mac上查看端口占用: lsof -i :${PORT}`);
    } else {
        console.error('服务器启动失败:', error);
    }
    process.exit(1);
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n正在关闭服务器...');
    wss.close(() => {
        server.close(() => {
            console.log('服务器已关闭');
            process.exit(0);
        });
    });
});

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
    console.error('未捕获的异常:', error);
    process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的Promise拒绝:', reason);
    process.exit(1);
}); 